package com.encap;

public class Encapsulation01 {
    public static void main(String[] args) {
        Person person = new Person();
        person.setName("anna");
        person.setAge(19);
        person.setSalary(30000);
        System.out.println(person.info());
        System.out.println(person.getSalary());

        //如果使用构造器指定属性
        Person betty = new Person("betty",200,30000);
        System.out.println(betty.info());

    }
}
/*
不能随便查看人的年龄，工资等隐私，并对设置的年龄进行合理的验证，
年龄合理就设置，否则就给默认年龄，必须在1-120，工资不能直接查看，
name的长度在2-6字符之间
 */
class Person{
    public String name;
    private int age;
    private double salary;

    //构造器


    public Person() {
    }
    //三个属性的构造器
    public Person(String name, int age, double salary) {
        this.name = name;
        this.age = age;
        this.salary = salary;
        //将set方法写在构造器中，这样仍然可以验证
        setName(name);
        setAge(age);
        setSalary(salary);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        //加入对数据的校验
        if(name.length() >= 2 && name.length() <= 6){
            this.name = name;
        }else{
            System.out.println("名字的长度需在2-6字符之间，默认名字");
            this.name = "默认用户";
        }

    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        //判断
        if(age >= 1 && age <= 120){
            this.age = age;
        }else{
            System.out.println("年龄超出可设置范围，需要在1-120，默认年龄18");
            this.age = 18;
        }

    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }
    //写一个方法，返回属性信息
    public String info(){
        return "信息为 name=" + name + " age=" + age + " salary=" + salary;
    }
}